Defining and Calling Methods in Java
Course: Core Java Training
Topic: Defining and Calling Methods in Java
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Methods in Java
A method in Java is a named block of code designed to perform a particular task. Methods help developers divide a large program into smaller, manageable, reusable components. Instead of writing the same instructions repeatedly, a developer can define a method once and call it whenever the operation is required.
Methods are fundamental to Java programming because they improve code organization, readability, maintainability, and reusability. They can perform calculations, display information, validate input, process data, and interact with objects.
For example, a banking application may contain methods for depositing money, withdrawing money, checking an account balance, and displaying transaction details.
Why Are Methods Important?
- Reusability: A method can be called multiple times without rewriting its implementation.
- Modularity: Large programs can be divided into smaller logical operations.
- Readability: Meaningful method names help explain what the code does.
- Maintainability: Changes to a specific operation can be made in one place.
- Testing: Individual methods can be tested independently.
- Debugging: Errors can be investigated within a smaller section of code.
- Abstraction: Callers can use a method without needing to understand every implementation detail.
2. What Does Defining a Method Mean?
Defining a method means declaring its name, return type, parameters, and implementation. The method definition specifies what the method does when it is invoked.
A method definition usually contains a method header followed by a body enclosed in curly braces.
General Syntax
accessModifier static returnType methodName(parameters) {
// Statements to perform the task
return value;
}
The static keyword is optional. The return statement is required when a method must return a value, except when the compiler recognizes that the method cannot complete normally, such as a method that always throws an exception.
Components of a Method Definition
| Component |
Description |
Example |
| Access modifier |
Controls the visibility of the method. |
public, private, protected |
| static keyword |
Declares a class-level method rather than an instance method. |
static |
| Return type |
Specifies the type of value returned by the method. |
int, double, String, void |
| Method name |
Identifies the method and is used when calling it. |
calculateTotal |
| Parameter list |
Declares the inputs accepted by the method. |
int a, int b |
| Method body |
Contains the instructions executed when the method is called. |
return a + b; |
| Return statement |
Returns a result to the calling code when required. |
return result; |
3. Creating Your First Java Method
The easiest way to understand method definition is to create a simple method that displays a message.
Example: Displaying a Welcome Message
public class Welcome {
static void displayMessage() {
System.out.println("Welcome to Core Java!");
}
public static void main(String[] args) {
displayMessage();
}
}
Output:
Welcome to Core Java!
Explanation
public class Welcome defines a class named Welcome.
static void displayMessage() defines a static method named displayMessage.
void indicates that the method does not return a value.
System.out.println() displays the message on the console.
main() is the program's entry point when the class is launched by the Java launcher.
displayMessage(); calls the method and executes its body.
Defining a method does not normally execute its body immediately. The method runs when it is invoked, unless it is invoked as part of another operation such as object initialization.
4. What Does Calling a Method Mean?
Calling a method means requesting the execution of the code defined inside that method. A method call can provide arguments, receive a returned value, or perform an operation without returning a result.
The syntax for calling a method depends on whether the method is static or an instance method.
Calling a Static Method
ClassName.methodName(arguments);
Calling an Instance Method
objectReference.methodName(arguments);
Example: Calling a Method Multiple Times
public class Greeting {
static void sayHello() {
System.out.println("Hello, Java Learner!");
}
public static void main(String[] args) {
sayHello();
sayHello();
sayHello();
}
}
Output:
Hello, Java Learner!
Hello, Java Learner!
Hello, Java Learner!
Explanation: The method is defined once and called three times. Each call executes the same method body, demonstrating code reuse.
5. Understanding Methods with Parameters
Parameters allow a method to receive information from the calling code. They make methods more flexible because the same method can operate on different inputs.
Parameters are declared inside the parentheses in the method definition. When the method is called, arguments provide the actual values or expressions used to initialize those parameters.
Example: Adding Two Numbers
public class Addition {
static void addNumbers(int a, int b) {
int sum = a + b;
System.out.println("Sum: " + sum);
}
public static void main(String[] args) {
addNumbers(10, 20);
addNumbers(50, 30);
addNumbers(100, 200);
}
}
Output:
Sum: 30
Sum: 80
Sum: 300
Explanation
int a and int b are formal parameters.
10, 20, 50, 30, and 100, 200 are arguments supplied during the calls.
- The method calculates the sum for each pair of arguments.
- The same implementation handles multiple sets of values.
Important Rule
The arguments supplied in a method call must be compatible with the method's parameter types and satisfy the applicable method invocation rules. The number and types of arguments must match an available method signature after Java applies permitted conversions and overload resolution.
6. Methods That Return Values
A method can calculate a result and send it back to the calling code using the return statement. This allows the returned value to be stored in a variable, printed, passed to another method, or used in an expression.
Example: Returning the Sum of Two Numbers
public class Calculator {
static int add(int a, int b) {
int sum = a + b;
return sum;
}
public static void main(String[] args) {
int result = add(15, 25);
System.out.println("Result: " + result);
}
}
Output:
Result: 40
How It Works
- The main() method calls add(15, 25).
- The values 15 and 25 are assigned to parameters a and b.
- The method calculates their sum.
- The return statement sends the result, 40, back to the caller.
- The returned value is assigned to the result variable.
- The program displays the value stored in result.
Using a Returned Value Directly
public class SquareCalculator {
static int square(int number) {
return number * number;
}
public static void main(String[] args) {
System.out.println(square(5));
System.out.println(square(8));
}
}
Output:
25
64
A method that returns a value can be used directly inside another expression or method call. This is often useful when calculations are combined.
7. Understanding the void Return Type
The void keyword indicates that a method does not return a value to its caller. Void methods are useful for actions such as displaying messages, printing reports, updating an object's state, or writing information to a file.
Example: Displaying Employee Details
public class EmployeeDetails {
static void displayEmployee() {
System.out.println("Employee Name: Rahul");
System.out.println("Department: IT");
System.out.println("Experience: 3 years");
}
public static void main(String[] args) {
displayEmployee();
}
}
Output:
Employee Name: Rahul
Department: IT
Experience: 3 years
Because displayEmployee() has a void return type, it cannot return a value such as an int or String. A bare return; statement may be used to exit a void method early.
Example: Early Return from a Void Method
public class NumberChecker {
static void checkNumber(int number) {
if (number < 0) {
System.out.println("Negative number");
return;
}
System.out.println("Zero or positive number");
}
public static void main(String[] args) {
checkNumber(-5);
checkNumber(10);
}
}
Output:
Negative number
Zero or positive number
When the argument is negative, the return statement exits the method before the final print statement executes.
8. Calling Instance Methods Using Objects
An instance method belongs to an object. To call an instance method from a static context such as main(), the program normally creates an object and invokes the method through its reference.
Example: Student Information
class Student {
String name;
int marks;
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Marks: " + marks);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.name = "Priya";
student.marks = 85;
student.displayDetails();
}
}
Output:
Name: Priya
Marks: 85
Explanation
Student is a class that defines student data and behavior.
new Student() creates a Student object.
- The student reference is used to access the object's fields.
student.displayDetails() calls the instance method on that object.
In production code, fields are commonly made private and accessed through constructors or suitable methods to preserve encapsulation.
9. Difference Between Static and Instance Methods
Java supports both static methods and instance methods. Choosing the appropriate kind helps keep program organization clear.
| Feature |
Static Method |
Instance Method |
| Association |
Associated with a class. |
Associated with an object. |
| Calling style |
Typically ClassName.methodName(). |
Typically objectReference.methodName(). |
| Object required |
No instance is required to invoke it. |
Normally requires an object receiver. |
| Instance fields |
Cannot directly access instance fields without an object reference. |
Can access the current object's instance fields. |
| Typical purpose |
General calculations and class-level utilities. |
Behavior involving an object's state. |
Example: Static and Instance Methods
class MathUtility {
static int multiply(int a, int b) {
return a * b;
}
}
class Rectangle {
private double length;
private double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double calculateArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtility.multiply(4, 5);
System.out.println("Product: " + result);
Rectangle rectangle = new Rectangle(10, 5);
System.out.println("Area: " + rectangle.calculateArea());
}
}
Output:
Product: 20
Area: 50.0
The multiply() method does not depend on object-specific data, so it is static. The calculateArea() method uses the dimensions stored in a Rectangle object, so it is an instance method.
10. Calling One Method from Another Method
A Java method can call another method to reuse its functionality or divide a complex operation into smaller steps. This improves modularity and helps avoid duplicated code.
Example: Calculating a Final Price
public class PriceCalculator {
static double calculateDiscount(double price) {
return price * 0.10;
}
static double calculateFinalPrice(double price) {
double discount = calculateDiscount(price);
return price - discount;
}
public static void main(String[] args) {
double finalPrice = calculateFinalPrice(1000);
System.out.println("Final Price: " + finalPrice);
}
}
Output:
Final Price: 900.0
Explanation: calculateFinalPrice() calls calculateDiscount() to obtain the discount amount. It then subtracts that amount from the original price and returns the result.
11. Understanding Method Signatures
A method signature identifies a method for declaration and overload resolution. In Java, the signature consists of the method name and the types of its formal parameters, with the relevant type parameters as specified by the language rules. The return type is not part of the method signature.
Example
class Display {
void show(int number) {
System.out.println(number);
}
void show(String message) {
System.out.println(message);
}
}
Both methods have the same name, show, but different parameter types. This is a valid example of method overloading.
However, Java does not allow two methods in the same class to differ only by return type.
// Invalid Java: return type alone cannot overload a method.
int calculate(int value) {
return value * 2;
}
// This declaration conflicts with the method above.
double calculate(int value) {
return value * 2.0;
}
The declarations conflict because both have the same name and parameter types.
12. Method Overloading
Method overloading allows a class to define multiple methods with the same name but different parameter lists. The compiler determines which overloaded method to invoke based on the arguments and Java's method resolution rules.
Overloaded methods can differ in the number of parameters, parameter types, or the order of parameter types.
Example: Overloaded Addition Methods
public class Addition {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(10, 20));
System.out.println(add(10, 20, 30));
System.out.println(add(2.5, 3.5));
}
}
Output:
30
60
6.0
Explanation: The compiler selects the suitable add() method according to the arguments provided. Overloading allows related operations to share a meaningful method name.
13. Passing Arguments to Methods
Arguments provide data to a method. Java is strictly pass-by-value: the method receives a copy of the argument value. For object arguments, the copied value is the object reference, so a method can use that reference to modify the referenced object's state, but reassigning the parameter does not change the caller's reference variable.
Example: Passing Primitive Values
public class ValueExample {
static void changeNumber(int number) {
number = 100;
}
public static void main(String[] args) {
int value = 10;
changeNumber(value);
System.out.println(value);
}
}
Output:
10
The method changes its local copy of the integer value. The original variable remains unchanged.
Example: Passing an Object Reference
class Box {
int value;
}
public class ObjectExample {
static void updateBox(Box box) {
box.value = 100;
}
public static void main(String[] args) {
Box myBox = new Box();
myBox.value = 10;
updateBox(myBox);
System.out.println(myBox.value);
}
}
Output:
100
The copied reference points to the same Box object. Changing the object's field through that reference is visible to the caller.
14. Calling Methods with Conditional Statements
Methods can be called from conditional statements to execute operations only when particular conditions are satisfied. This technique is useful for validation, eligibility checks, and business rules.
Example: Checking Voting Eligibility
public class VotingEligibility {
static boolean isEligible(int age) {
return age >= 18;
}
public static void main(String[] args) {
int age = 20;
if (isEligible(age)) {
System.out.println("Eligible to vote.");
} else {
System.out.println("Not eligible to vote.");
}
}
}
Output:
Eligible to vote.
The isEligible() method returns a boolean value. The if statement uses that result to choose the appropriate message.
15. Calling Methods Using Loops
Methods can be called repeatedly inside loops when an operation must be performed for multiple values. This reduces duplication and makes repeated processing easier to manage.
Example: Printing Squares of Numbers
public class SquarePrinter {
static int square(int number) {
return number * number;
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(
"Square of " + i + " = " + square(i)
);
}
}
}
Output:
Square of 1 = 1
Square of 2 = 4
Square of 3 = 9
Square of 4 = 16
Square of 5 = 25
The loop supplies a different argument to square() during each iteration. The method calculates and returns the square of that value.
16. Common Errors When Defining and Calling Methods
| Error |
Explanation |
Solution |
| Calling a method without required arguments |
The call does not match an available method declaration. |
Supply the required arguments with compatible types. |
| Using an incorrect return type |
The returned expression may not be compatible with the declared return type. |
Return a compatible value or change the method declaration appropriately. |
| Missing return statement |
A non-void method may complete normally without returning a value. |
Ensure every reachable normal completion path returns a suitable value. |
| Calling an instance method directly from static context |
There is no implicit current object in a static method. |
Create an object and call the instance method through it. |
| Using a local variable before initialization |
Java requires local variables to be definitely assigned before use. |
Initialize the variable before reading it. |
| Using duplicate method signatures |
Conflicting declarations cannot be distinguished by return type alone. |
Change the parameter list or use a distinct method name. |
| Incorrect capitalization |
Java identifiers are case-sensitive. |
Use the exact method name, such as calculateTotal() rather than calculatetotal(). |
| Creating methods with too many responsibilities |
Complex methods are difficult to test and maintain. |
Divide the operation into smaller, cohesive methods. |
17. Best Practices for Defining and Calling Methods
- Use descriptive names that communicate the purpose of each method.
- Follow Java naming conventions and use lower camel case for method names.
- Keep methods focused on a clear responsibility.
- Use parameters instead of hardcoding values that may change.
- Choose the correct return type based on the result the caller needs.
- Use void for methods that perform actions without returning a value.
- Prefer instance methods for behavior that depends on object state.
- Use static methods for operations that do not require instance-specific state.
- Validate input when required by the method's responsibility.
- Avoid unnecessary duplication by reusing existing methods.
- Keep access modifiers as restrictive as practical.
- Test normal inputs, boundary conditions, and invalid inputs.
- Use comments to explain non-obvious decisions rather than restating every line of code.
18. Practical Project: Simple Calculator Using Methods
This beginner-friendly project demonstrates how to define and call multiple methods in one Java application.
Project Requirements
- Create separate methods for addition, subtraction, multiplication, and division.
- Pass numbers as method arguments.
- Return calculation results to the calling code.
- Display each result in the console.
- Handle division by zero appropriately.
Complete Java Program
public class SimpleCalculator {
static double add(double a, double b) {
return a + b;
}
static double subtract(double a, double b) {
return a - b;
}
static double multiply(double a, double b) {
return a * b;
}
static double divide(double a, double b) {
if (b == 0) {
throw new IllegalArgumentException(
"Division by zero is not allowed."
);
}
return a / b;
}
public static void main(String[] args) {
double a = 20;
double b = 5;
System.out.println("Addition: " + add(a, b));
System.out.println("Subtraction: " + subtract(a, b));
System.out.println("Multiplication: " + multiply(a, b));
System.out.println("Division: " + divide(a, b));
}
}
Output:
Addition: 25.0
Subtraction: 15.0
Multiplication: 100.0
Division: 4.0
Project Explanation
- The SimpleCalculator class contains four reusable static methods.
- Each method accepts two double arguments.
- The arithmetic methods return their calculated results.
- The divide() method checks whether the second argument is zero before dividing.
- The main() method calls all four methods and displays their results.
19. Practice Exercises
Beginner Exercises
- Define a method named greetUser() that prints a welcome message.
- Write a method that accepts two integers and returns their sum.
- Create a method that returns the square of a number.
- Define a method that checks whether a number is even or odd.
- Write a method that accepts a name and prints a personalized greeting.
Intermediate Exercises
- Create a method to calculate the factorial of a positive integer.
- Write a method that returns the largest of three numbers.
- Define overloaded methods for calculating the area of a square, rectangle, and circle.
- Create a Student class with an instance method to display student details.
- Write a method that calculates the final price after applying a discount.
Advanced Exercise
Create an employee salary application containing an Employee class and an EmployeeService class. Define methods to calculate monthly salary, annual salary, and bonus. Call these methods from main(), validate inputs, and display the results. Organize the methods according to their responsibilities.
20. Interview Questions and Answers
Q1. What is a method in Java?
Answer: A method is a named block of code that performs a specific task. It can accept parameters, execute statements, and return a result.
Q2. What is the difference between defining and calling a method?
Answer: Defining a method specifies its signature and implementation. Calling a method invokes it so its body executes.
Q3. What is the purpose of the return statement?
Answer: The return statement terminates a method and can provide a value to the caller when the method has a non-void return type.
Q4. What is the difference between void and int return types?
Answer: A void method does not return a value, while an int method returns an integer value when it completes normally.
Q5. What are parameters and arguments?
Answer: Parameters are variables declared in a method definition. Arguments are the values or expressions supplied in a method call.
Q6. Can a method call another method?
Answer: Yes. A method can call another method to reuse functionality or divide a complex task into smaller operations.
Q7. Can a Java method return multiple values directly?
Answer: A method has one declared return type. Multiple related values can be grouped in an object, record, array, or collection and returned together.
Q8. Can two methods have the same name?
Answer: Yes. Method overloading permits methods with the same name when their parameter lists differ appropriately.
Q9. Can a static method call an instance method directly?
Answer: Not without an object receiver. A static method can call an instance method through a suitable object reference.
Q10. What happens when a method is called multiple times?
Answer: The method body executes for each call. Each invocation has its own method parameters and local variables, while shared object or class state may persist according to how it is defined.
Q11. What is method reusability?
Answer: Method reusability means using the same method implementation in multiple places instead of duplicating its logic.
Q12. Why should methods have meaningful names?
Answer: Meaningful names communicate the purpose of the operation and improve code readability and maintainability.
21. Quick Revision Notes
- A method is a named block of reusable Java code.
- A method definition includes a name, return type, parameters, and body.
- A method call invokes the method's implementation.
- Parameters receive argument values supplied by callers.
- The return statement can send a result back to the caller.
- The void keyword indicates that a method does not return a value.
- Static methods are associated with the class.
- Instance methods operate through objects.
- Method overloading allows the same name with different parameter lists.
- Java uses pass-by-value for both primitive values and object references.
- Methods can be called from loops, conditional statements, and other methods.
- Well-designed methods improve modularity, testing, readability, and reuse.
22. Conclusion
Defining and calling methods is one of the most important fundamentals of Core Java programming. Method definitions specify how operations work, while method calls execute those operations with the required arguments. Return types, parameters, static methods, instance methods, and method overloading provide the flexibility needed to build organized Java applications.
Practice by creating small programs such as calculators, number checkers, student management applications, and employee salary systems. As your understanding improves, combine methods with classes, constructors, encapsulation, and packages to develop more maintainable applications.
Explore additional concepts through the JustAcademy Core Java Training Course, or register for a course demo to learn more about the training.
Visit JustAcademy for more learning resources.